<?php

/**
 * 支付宝支付
 */

namespace App\Services\AliPay;


use App\Models\Panx\SkinRecordBonus;
use App\Services\Utils\TimeHelper;

define("AOP_SDK_WORK_DIR",storage_path('logs/')); // win环境下不加会 invalid [default store dir]: /tmp/ ？？？
require(app_path('Libs/Ali/OpenPlatform/AopSdk.php'));

class AopFactory
{
    /**
     * @var \AopClient $aop
     */
    private $sandbox_aop;

    /**
     * @var \AopClient $aop
     */
    private $production_aop;

    const TRANSFER_SUCCESS = '10000';

    const SANDBOX_PAYEE_ACCOUNT = 'etnxoj0265@sandbox.com';

    /**
     * AppFactory constructor.
     */
    public function __construct()
    {
        // 沙箱
        $this->sandbox_aop = new \AopClient;
        // @link https://openhome.alipay.com/platform/appDaily.htm?tab=info - 沙箱网关
        $this->sandbox_aop->gatewayUrl = 'https://openapi.alipaydev.com/gateway.do';
        $this->sandbox_aop->appId = config('pkx.ali.open_platform.app_id_sandbox');
        $this->sandbox_aop->rsaPrivateKey = file_get_contents(app_path('certs/ali/open_platform/panx_private.key'));
        $this->sandbox_aop->alipayrsaPublicKey = file_get_contents(app_path('certs/ali/open_platform/alipay_public_sandbox.key'));
        $this->sandbox_aop->signType = "RSA2";

        // 真实
        $this->production_aop = new \AopClient;
        $this->production_aop->appId = config('pkx.ali.open_platform.app_id');
        $this->production_aop->rsaPrivateKey = file_get_contents(app_path('certs/ali/open_platform/panx_private.key'));
        $this->production_aop->alipayrsaPublicKey = file_get_contents(app_path('certs/ali/open_platform/alipay_public.key'));
        $this->production_aop->signType = "RSA2";
    }

    public function sandboxAop()
    {
        return $this->sandbox_aop;
    }

    public function productionAop()
    {
        return $this->production_aop;
    }

    public function Aop()
    {
        return config('app.debug')
            ? (new AopFactory())->sandboxAop()
            : (new AopFactory())->productionAop();
    }

    /**
     * @param SkinRecordBonus $skinRecordBonus
     *
     * @return mixed
     * @throws \Exception
     */
    public function transferRequestForSkinRecordBonus(SkinRecordBonus $skinRecordBonus)
    {
        $payee_account = config('app.debug')
            ? self::SANDBOX_PAYEE_ACCOUNT
            : $skinRecordBonus->bonusable->ali_account;

        /**
         * @link https://docs.open.alipay.com/api_28/alipay.fund.trans.toaccount.transfer - 参数
         */
        $request = new \AlipayFundTransToaccountTransferRequest();

        $request->setBizContent(json_encode([
            "out_biz_no"    => TimeHelper::microTimeSerial(),
            "amount"        => number_format($skinRecordBonus->amount, 2, '.', ''),
            "payee_type"    => 'ALIPAY_LOGONID',
            "payee_account" => $payee_account,
        ]));

        return $this->Aop()->execute($request);
    }

}